// Render a link for adding hCalendar events to Google Calendar.
// version 1.0
// 2006-07-08
// Copyright (c) 2006, Calvin Yu
//
// --------------------------------------------------------------------
//
// This is a Tails script.
//
// To install, you need Tails: http://blog.codeeg.com/tails-firefox-extension/
// Then restart Firefox and revisit this script and click on 'Install'.
//
// To uninstall, go to Tools/Manage Tails Scripts...,
// select "Add to GCal", and click Uninstall.
//
// --------------------------------------------------------------------
//
// ==TailsScript==
// @name          Add to GCal
// @namespace     http://blog.codeeg.com/tails
// @description   Render a link for adding hCalendar events to Google Calendar.
// @include       hcalendar
// ==/TailsScript==

getURL: function() {
  var hcal = this.object;

  var url = "http://www.google.com/calendar/event?action=TEMPLATE";

  if (hcal.summary) url += "&text=" + this.attrEscape(hcal.summary);

  var description = "[from: " + this.sourceURL + "] ";
  if (hcal.description) description += hcal.description;

  url += "&details=" + this.attrEscape(description);

  var dates = (hcal.dtstart_date && hcal.dtend_date)
      ? (this.toGDateString(hcal.dtstart_date) + "/" + this.toGDateString(hcal.dtend_date))
      : (hcal.dtstart_date ? this.toGDateString(hcal.dtstart_date) + "/" + this.toGDateString(hcal.dtstart_date) : null);
  if (dates) url += "&dates=" + dates;
  else { 
    // dates are required
    return null;
  }

  var location = null;
  if (hcal.location_hcard
      && hcal.location_hcard['street-address']
      && ((hcal.location_hcard.locality && hcal.location_hcard.region)
      || hcal.location_hcard['postal-code'])) {

    location = hcal.location_hcard.toAddressString();

  } else if (hcal.location) {
    location = hcal.location;
  }
  if (location) url += "&location=" + this.attrEscape(location);

  url += "&sprop=" + this.attrEscape(this.sourceURL) + "&sprop=name:website";
  if (hcal.url) {
    url += "&sprop=" + this.attrEscape(hcal.url) + "&sprop=name:website";
  }
//alert(url);
  return url;
},

toGDateString: function(dt) {
  return "" + dt.getUTCFullYear() + this.leftPad(dt.getUTCMonth()+1,2)
      + this.leftPad(dt.getUTCDate(),2) + "T" + this.leftPad(dt.getUTCHours(),2)
      + this.leftPad(dt.getUTCMinutes(),2) + "00Z";
},
leftPad: function(n, len) {
  var s = String(n);
  var spaces = len - s.length;
  for (var i=0; i<spaces; i++) {
    s = "0" + s;
  }
  return s;
},
attrEscape: function(v) {
  return v.replace(/\'/g, "&apos;");
}

